// **************************************************************
// Com ++ Framework by the C++ World
// Please report defects: mailto:compp@cplusplusworld.com
// Please visit: http://www.cplusplusworld.com/socketlibrary.html
// **************************************************************

#include "ComPlusPlus/Launch.h"
#include "SysPlusPlus/ComException.h"
#include "SysPlusPlus/Tools.h"
#include <unistd.h>
#include <string.h>

/**
  * clones process and executes cmd
  */
compp::Launch::Launch( const std::string & cmd ) : Clone (cmd)  {

  Command = cmd;

  char *sub, *saveptr ;
  int i =0;
  char *token, *orig = strdup ( Command.c_str() );

  for (  token = orig; ;token = NULL ) {
    sub = strtok_r ( token , " ", &saveptr );
    if ( NULL != sub )
      mArgv [ i ] = strdup(sub);
    else
      mArgv [ i ] = NULL;

    if (sub == NULL) {
      break;
    }
    ++i;
  }

}

/**
 * Destructor
 **/
compp::Launch::~Launch() {

}

int compp::Launch::Spawn( ) {

  if ( false == syspp::Tools::IsExecutable ( mArgv[0] ) ) {
    std::string errstr=  "Cannot Launch: execv() failed: " ;
    errstr += Command;
    errstr += " err = ";
    errstr += strerror ( errno );
    throw syspp::ComException ( errstr.c_str() );
  }
  Start();
  return 0;
}

int compp::Launch::Run ( ) {

  execv (   mArgv[0], mArgv ) ;
  std::string errstr=  "Cannot Launch ( execv() failed: " ;
  errstr += Command;
  errstr += " err = ";
  errstr += strerror ( errno );

  throw syspp::ComException ( errstr.c_str() );

  return -1;
}

void compp::Launch::SetCommand (const std::string &cmdargs) {

  this->Command = cmdargs;  

}
